<script setup>
import { useHotPostQuery } from '@/composables/usePostDataQuery'
import { useHotDiscussQuery } from '@/composables/useTopicDataQuery'
import { useHotUpperQuery } from '@/composables/useUserInfoQuery'
import FansListItem from '@/views/UserHome/components/FansListItem.vue'
import { useRouter, useRoute } from 'vue-router'
import ContainerSplitOrFull from '@/components/commonUI/ContainerSplitOrFull.vue'
import HotPostItem from '@/components/HotPostItem.vue'
import { MessageBox, View } from '@element-plus/icons-vue'
import { ref, watch, computed, reactive } from 'vue'
import { get } from '@/axios/utils/request'
import PostTopItem from '@/components/PostTopItem.vue'
import top from '/imgs/commonIcons/top.svg'
import LfButton from '@/components/commonUI/LfButton.vue'

// import { useGlobalStore } from '@/stores/globalStore'
// const globalStore = useGlobalStore()
// const postFilter = computed(() => globalStore.postFilter)

const props = defineProps({
  topicId: String,
})

const tabIndex = ref(0) // 0:热门 1:最新
onMounted(() => {
  tabIndex.value = sessionStorage.getItem('tabIndex') || 0

  if (tabIndex.value == 1) {
    latestPage.value = 1
    fetchLatestPosts(true)
  } else if (tabIndex.value == 2) {
    essencePostPage.value = 1
    fetchEssencePosts(true)
  }
  fetchTopPosts()
})

// const { data: hotPost } = useHotPostQuery()
const hotPostParams = reactive({
  page: 1,
  limit: 10,
  topicIds: props.topicId
})
const router = useRouter()
const route = useRoute()
const topicId = computed(() => props.topicId)
const {
  data: hotPost,
  fetchNextPage: fetchHotPostNextPage,
  hasNextPage: hotPostHasNextPage,
  isFetching: hotPostIsFetching,
  isLoading: hotPostIsLoading,
  refetch: hotPostRefetch
} = useHotPostQuery(topicId)

const hotPostList = computed(() =>
  hotPost.value?.pages?.flatMap(page => page.hotPost || []) || []
)

const handleHotPostScroll = (e) => {
  const el = e.target
  if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10 && hotPostHasNextPage.value && !hotPostIsFetching.value) {
    fetchHotPostNextPage()
  }
}

const { data: hotUpper } = useHotUpperQuery()
const { data: hotDiscuss } = useHotDiscussQuery()


//全站置顶帖相关
const postTopList = ref([])
const fetchTopPosts = async () => {
  try {
    const res = await get('/post/topPost')
    if (res.code === 0 && res.result && Array.isArray(res.result)) {
      postTopList.value = res.result
    }
  } finally {
  }
}

// 最新帖子相关
const latestPostList = ref([])
const latestPage = ref(1)
const latestHasNext = ref(true)
const latestLoading = ref(false)

const fetchLatestPosts = async (reset = false) => {
  if (latestLoading.value) return
  latestLoading.value = true
  try {
    const res = await get('/post/lastPostByFilter', { page: latestPage.value, filter: 0, type: 0, limit: 20, topicIds: topicId.value })
    if (res.code === 0 && res.result && Array.isArray(res.result.data)) {
      if (reset) {
        latestPostList.value = res.result.data || []
      } else {
        latestPostList.value = latestPostList.value.concat(res.result.data)
      }
      latestHasNext.value = res.result.current_page < res.result.total
    }
  } finally {
    latestLoading.value = false
  }
}

const handleLatestScroll = (e) => {
  latestPage.value++
    fetchLatestPosts()
  // const el = e.target
  // if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10 && latestHasNext.value && !latestLoading.value) {
  //   latestPage.value++
  //   fetchLatestPosts()
  // }
}
//刷新喜欢接口数据
const refreshCollection = (e) => {
  if(tabIndex.value == 0) {
    hotPostRefetch()
  } else if (tabIndex.value == 1) {
    fetchLatestPosts(true)
  } else if (tabIndex.value == 2) {
    fetchEssencePosts(true)
  }
}



watch(tabIndex, (idx) => {
  sessionStorage.setItem('tabIndex', idx)
  if (idx == 1) {
  // if (idx === 1 && latestPostList.value.length === 0) {
    latestPage.value = 1
    fetchLatestPosts(true)
  }
  if (idx == 2) {
  // if (idx === 2 && essencePostList.value.length === 0) {
    essencePostPage.value = 1
    fetchEssencePosts(true)
  }
})

watch(topicId, (newVal) => {
   if (tabIndex.value == 1) {
      latestPage.value = 1
      fetchLatestPosts(true)
    } else if (tabIndex.value == 2) {
       essencePostPage.value = 1
      fetchEssencePosts(true)
    }
})


// watch(hotPost, (newVal) => {
//   console.log(newVal);
// })
const handleDiscussClick = (item) => {
  // router.push(`/topic/${item.topicId}/discuss/${item.id}`)
  router.push(`/topic/${item.topicId}/discuss/${item.id}`)

  // router.push(`/home/post/${item.id}`)
}

const handleMore = (type) => {
  let url = type == 1 ? '/topicExplore' : '/hotPost?type=1'
  router.push(url)
}
//显示社区置顶帖
const activeNames = ref(['1'])
//精华帖相关
const essencePostList = ref([])
const essencePostPage = ref(1)
const essencePostHasNext = ref(true)
const essencePostLoading = ref(false)

const fetchEssencePosts = async (reset = false) => {
  if (essencePostLoading.value) return
  essencePostLoading.value = true
  try {
    const res = await get('/post/getEssencePostList', { page: essencePostPage.value, filter: 0, type: 0, limit: 20, topicIds: topicId.value })
    if (res.code === 0 && res.result && Array.isArray(res.result.data)) {
      if (reset) {
        essencePostList.value = res.result.data
      } else {
        essencePostList.value = essencePostList.value.concat(res.result.data)
      }
      essencePostHasNext.value = res.result.current_page < res.result.last_page
    }
  } finally {
    essencePostLoading.value = false
  }
}
const handleEssencePostScroll = (e) => {
  const el = e.target
  if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10 && essencePostHasNext.value && !essencePostLoading.value) {
    essencePostPage.value++
    fetchEssencePosts()
  }
}

</script>
<template>
  <div class="flex w-full pt-[20px] max-w-[1600px] mx-auto">
    <div class="flex-1 border-1 border-slate-200 rounded-xl pt-0 p-3 mr-2 hot-post-scroll"
      :class="tabIndex === 1 ? 'latest-scroll' : ''"
      @scroll="tabIndex === 0 ? handleHotPostScroll : tabIndex === 1 ? handleLatestScroll : handleEssencePostScroll">
      <div class="hot-tab-bar-sticky flex items-center gap-6 mb-2" style="    height: 50px;">
        <span :class="['hot-tab-text', tabIndex == 0 ? 'active' : '']" @click="tabIndex = 0">热门帖子</span>
        <span :class="['hot-tab-text', tabIndex == 1 ? 'active' : '']" @click="tabIndex = 1"
          v-if="!route.query.type">最新帖子</span>
        <span :class="['hot-tab-text', tabIndex == 2 ? 'active' : '']" @click="tabIndex = 2">精华帖子</span>
        <span class="flex-1 text-right text-[#2e5592] hover:text-[#16437C] hover:underline cursor-pointer"
          @click="handleMore(tabIndex)" v-if="!route.query.type">更多</span>

      </div>
      <div class="flex gap-2 flex-col min-h-[200px]">
        <template v-if="postTopList.length > 0 && !props.topicId">
          <el-collapse accordion v-model="activeNames">
            <el-collapse-item name="1">
              <template #title="{ isActive }">
                <div :class="['title-wrapper', { 'is-active': isActive }]" class="top-wrapper-title">
                  <el-icon class="header-icon">
                    <img :src="top" alt="" />
                  </el-icon>
                  社区置顶帖
                </div>
              </template>
              <PostTopItem v-for="item in postTopList" :key="item.id" :data="item"></PostTopItem>
            </el-collapse-item>
          </el-collapse>
        </template>
        <template v-if="tabIndex == 0">
          <template v-if="hotPostList.length > 0">
            <HotPostItem @refreshCollection="refreshCollection" v-for="item in hotPostList" :key="item.id" :data="item" />
            <div v-if="hotPostIsFetching" class="text-center text-gray-400 py-2">加载中...</div>
            <div v-if="!hotPostHasNextPage && !hotPostIsFetching" class="text-center text-gray-400 py-2">没有更多数据了</div>
          </template>
          <div v-else class="flex flex-col items-center justify-center py-8 text-gray-400">
            <img src="/src/assets/empty-expert.svg" alt="暂无数据" class="w-24 h-24 mb-2 opacity-80" />
            <div>暂无数据</div>
          </div>
        </template>
        <template v-else-if="tabIndex == 1">
          <template v-if="latestPostList.length > 0">
            <HotPostItem @refreshCollection="refreshCollection" v-for="item in latestPostList" :key="item.id" :data="item" />
            <div v-if="latestLoading" class="text-center text-gray-400 py-2">加载中...</div>
            <div v-if="!latestHasNext && !latestLoading" class="text-center text-gray-400 py-2">没有更多数据了</div>
            <div v-if="latestHasNext && !latestLoading" class="text-center text-[#2e5592] hover:text-[#16437C] hover:underline cursor-pointer" @click="handleLatestScroll">加载更多</div>
            <!-- <div v-else class="text-center text-gray-400 py-2">没有更多数据了</div> -->

         </template>
          <div v-else class="flex flex-col items-center justify-center py-8 text-gray-400">
            <img src="/src/assets/empty-expert.svg" alt="暂无数据" class="w-24 h-24 mb-2 opacity-80" />
            <div>暂无数据</div>
          </div>
        </template>
        <template v-else-if="tabIndex == 2">
          <template v-if="essencePostList.length > 0">
            <HotPostItem @refreshCollection="refreshCollection" v-for="item in essencePostList" :key="item.id" :data="item" />
            <div v-if="latestLoading" class="text-center text-gray-400 py-2">加载中...</div>
            <div v-if="!latestHasNext && !latestLoading" class="text-center text-gray-400 py-2">没有更多数据了</div>
          </template>
          <div v-else class="flex flex-col items-center justify-center py-8 text-gray-400">
            <img src="/src/assets/empty-expert.svg" alt="暂无数据" class="w-24 h-24 mb-2 opacity-80" />
            <div>暂无数据</div>
          </div>
        </template>
        <!-- <div @click="router.push('/forumStatistics')" class="home_tg">论坛统计</div> -->
      </div>
    </div>

    <div class="">
      <div v-if="hotUpper?.result.length > 0"
        class="w-[330px] h-[400px] overflow-y-auto border-1 border-slate-200 rounded-xl p-3">
        <div class="hot-section-title">热门博主</div>
        <div class="flex gap-2 flex-col">
          <FansListItem v-for="item in hotUpper.result" :key="item.id" :item="item" type="hot" />
        </div>
      </div>

      <div class="w-[330px] h-[400px] overflow-y-auto border-1 border-slate-200 rounded-xl p-3">
        <div class="hot-section-title">热门话题</div>
        <div class="flex gap-2 flex-col" v-if="hotDiscuss && hotDiscuss.result && hotDiscuss.result.length > 0">
          <div v-for="item in hotDiscuss.result" :key="item.id"
            class="flex justify-between items-end cursor-pointer hot-topic-item group"
            @click="handleDiscussClick(item)">
            <div class="flex flex-col gap-1 min-w-0">
              <div class="flex items-center gap-1 font-medium text-base text-blue-900 group-hover:text-blue-600">
                <el-icon class="text-blue-400">
                  <MessageBox />
                </el-icon>
                <span class="truncate max-w-[160px]"># {{ item.title }}</span>
              </div>
              <div class="text-sm text-slate-500 truncate max-w-[180px]">{{ item.introduce }}</div>
            </div>
            <div class="flex items-center gap-1 text-xs text-slate-500 flex-shrink-0">
              <el-icon class="text-gray-400">
                <View />
              </el-icon>
              <span>{{ item.readCount }}浏览</span>
            </div>
          </div>
        </div>
        <div v-else class="flex flex-col items-center justify-center py-8 text-gray-400">
          <img src="/src/assets/empty-expert.svg" alt="暂无话题" class="w-20 h-20 mb-2 opacity-80" />
          <div>暂无话题</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.home_tg {
  display: flex;
  justify-content: center;
  cursor: pointer;
  /* 字体灰色 */
  color: #999;
  font-size: 14px;
}

.top-wrapper-title {
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.hot-section-title {
  font-size: 20px;
  font-weight: 700;
  color: #1765ad;
  letter-spacing: 1px;
  margin-bottom: 18px;
  padding-left: 0;
  position: relative;
  line-height: 1.2;
}

.hot-section-title::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 22px;
  background: linear-gradient(135deg, #4f9cff 0%, #1765ad 100%);
  border-radius: 4px;
  margin-right: 12px;
  vertical-align: middle;
}

.hot-topic-item {
  border-radius: 10px;
  padding: 8px 10px;
  transition: background 0.18s;
}

.hot-topic-item:hover {
  background: #fafdff;
}

.hot-post-scroll,
.latest-scroll {
  /* max-height: 812px; */
  overflow-y: auto;
}

@media (max-width: 1920px) {

  .hot-post-scroll,
  .latest-scroll {
    max-height: 1000px;
  }
}

@media (min-width: 1920px) {

  .hot-post-scroll,
  .latest-scroll {
    max-height: 1220px;
  }
}

/* @media (max-width: 1680px) {
  .hot-post-scroll, .latest-scroll {
    max-height: 700px;
  }
} */
/* @media (max-width: 1440px) {
  .hot-post-scroll, .latest-scroll {
    max-height: 600px;
  }
}
@media (max-width: 1280px) {  
  .hot-post-scroll, .latest-scroll {
    max-height: 500px;
  }
}
@media (max-width: 1024px) {
  .hot-post-scroll, .latest-scroll {  
    max-height: 400px;
  }
} */
.hot-tab-text {
  font-size: 18px;
  font-weight: 600;
  color: #1765ad;
  cursor: pointer;
  margin-right: 24px;
  padding-bottom: 2px;
  border-bottom: 2px solid transparent;
  transition: color 0.18s, border 0.18s;
}

.hot-tab-text.active {
  color: #1765ad;
  border-bottom: 2.5px solid #1765ad;
}

.hot-tab-text:hover {
  color: #1765ad;
  border-bottom: 2.5px solid #4f9cff;
}

.hot-tab-text:last-child {
  margin-right: 0;
}

.hot-tab-bar-sticky {
  position: sticky;
  top: 0;
  z-index: 10;
  background: #fff;
  /* 可选：加个阴影或边框，提升层次感 */
  box-shadow: 0 2px 8px rgba(56, 112, 255, 0.04);
}
</style>
